package com.athuahua.spzx.controller;

import com.athuahua.spzx.dto.h5.UserLoginDto;
import com.athuahua.spzx.dto.h5.UserRegisterDto;
import com.athuahua.spzx.vo.ProductSkuPageVo;
import com.athuahua.spzx.exception.CodeException;
import com.athuahua.spzx.properties.JwtProperties;
import com.athuahua.spzx.service.UserBrowseHistoryService;
import com.athuahua.spzx.service.UserInfoService;
import com.athuahua.spzx.utils.BaseContext;
import com.athuahua.spzx.utils.JwtUtil;
import com.athuahua.spzx.utils.Result;
import com.athuahua.spzx.utils.ResultCodeEnum;
import com.athuahua.spzx.vo.h5.UserInfoVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author: huahua
 * @Date: 2024/8/13 0013
 * @Time: 15:27
 * @Description:
 */
@RestController
@RequestMapping("api/user/userInfo")
@Slf4j
@Tag(name = "用户模块")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserBrowseHistoryService userBrowseHistoryService;

    @PostMapping("register")
    public Result register(@RequestBody UserRegisterDto userRegisterDto) {
        log.info("register user: {}", userRegisterDto);

        userInfoService.register(userRegisterDto);


        return Result.success();
    }

    /**
     * 登录流程
     * 1.请求登录，验证用户信息和密码
     * 2.生成jwt
     * 3.返回jwt
     */

    @PostMapping("login")
    public Result login(@RequestBody UserLoginDto userLoginDto) {
        log.info("login user: {}", userLoginDto);
        String jwt = userInfoService.login(userLoginDto);


        return Result.success(jwt);
    }


    /**
     * 获取当前用户信息
     * 1.获取token
     * 2.解析token
     *
     * @return
     */
    @GetMapping("auth/getCurrentUserInfo")
    public Result<UserInfoVo> getCurrentUserInfo() {
        UserInfoVo userInfoVo = userInfoService.getCurrentUserInfo();


        return Result.success(userInfoVo);
    }

    /**
     * 请求 URL:
     * http://localhost:8500/api/user/userInfo/logout
     * 请求方法:
     * GET
     * 退出登录
     */

    @GetMapping("logout")
    public Result logout() {
        //使用jwt退出登录，不需要进行任何操作
        return Result.success();
    }




    //get http://localhost:8500/api/user/userInfo/isCollect/3 是否是收藏
    @GetMapping("isCollect/{skuId}")
    public Result<Boolean> isCollect(@PathVariable("skuId") Long skuId) {
        //1.未登陆返回false, 登录才查询
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return Result.success(false);
        } else {
            try {
                Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
                Long userId = Long.valueOf(claims.get("userName").toString());
                //设置当前登录用户id
                BaseContext.setCurrentId(userId);

            } catch (NumberFormatException e) {
                throw new CodeException(ResultCodeEnum.DATA_ERROR);
            }
        }

        boolean isCollect = userInfoService.isCollect(skuId);

        return Result.success(isCollect);
    }

    //get http://localhost:8500/api/user/userInfo/auth/collect/3 添加收藏
    @GetMapping("auth/collect/{skuId}")
    public Result collect(@PathVariable("skuId") Long skuId) {
        userInfoService.collect(skuId);


        return Result.success();
    }

    //get http://localhost:8500/api/user/userInfo/auth/cancelCollect/3 取消收藏
    @GetMapping("auth/cancelCollect/{skuId}")
    public Result cancelCollect(@PathVariable("skuId") Long skuId) {
        userInfoService.cancelCollect(skuId);
        return Result.success();
    }


    /**
     * 请求 URL:
     * http://localhost:8500/api/user/userInfo/auth/findUserBrowseHistoryPage/1/10
     * 请求方法:
     * GET
     * 历史记录分页查询
     **/
    @GetMapping("auth/findUserBrowseHistoryPage/{page}/{size}")
    public Result findUserBrowseHistoryPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        ProductSkuPageVo result = userBrowseHistoryService.findUserBrowseHistoryPage(page, size);

        return Result.success(result);
    }

    /**
     * openfeign 远程调用，保存用户浏览记录
     */
    @GetMapping("auth/saveUserBrowseHistory/{skuId}")
    public Result saveUserBrowseHistory(@PathVariable("skuId") Long skuId) {
        userBrowseHistoryService.saveUserBrowseHistory(skuId);

        return Result.success();
    }


}
